package extractor;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FilenameFilter;

import java.io.IOException;

import map.MapReader;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.encryption.AccessPermission;

class PDFFile implements FilenameFilter {
	String ext;

	public PDFFile() {
	}

	public boolean accept(File dir, String name) {
		return name.toLowerCase().endsWith(".pdf");
	}
}

public class PDFReader {
	private File[] Files;
	
	
	public PDFReader(String path) throws IOException {
		File file = new File(path);
		if (file.isDirectory()) {
			Files = file.listFiles(new PDFFile());
		} else
			throw new IOException("cannot find input directory");
	}

	public static void main(String[] args) throws Exception {
		PDFReader reader = new PDFReader(MapReader.input_year_pdf);
		reader.SaveImage(MapReader.png_year_path,MapReader.year_filename_prefix,MapReader.year_filename_suffix);
		reader = new PDFReader(MapReader.input_month_pdf);
		reader.SaveImage(MapReader.png_month_path,MapReader.month_filename_prefix,MapReader.month_filename_suffix);
	}

	public void SaveImage(String path,String prefix, String suffix) throws IOException {

		PDDocument doc = null;
		for (File pdf : Files) {
			String[] names=(pdf.getName().split(".pdf")[0]).split("_");

			if(names.length<=1)
				continue;
			String dig=names[names.length-1];
			System.out.println("loading "+pdf.getName()+"...");
			doc = PDDocument.load(pdf);
			AccessPermission ap = doc.getCurrentAccessPermission();

			if (doc.isEncrypted()) {
				throw new IOException("Error: You need password.");
			}

			if (!ap.canExtractContent()) {
				throw new IOException(
						"Error: You do not have permission to extract images.");
			}

			System.out.println("loading acomplished");
			String outPath=path;
			MapImageWriter writer = new MapImageWriter();
			if(!path.endsWith("\\"))
				outPath= path+"\\";
			File outDir= new File(path);
			if(!outDir.exists()||!outDir.isDirectory())
				throw new IOException("cannt find output directory");
			System.out.println("Writing "+prefix+dig+suffix+"...");
			writer.writeImage(doc, "png", null, 1, doc.getNumberOfPages(), outPath+prefix+dig+suffix,
					BufferedImage.TYPE_INT_RGB, MapReader.RES);
			System.out.println("Writing accomplished");

			doc.close();
		}

		

		System.out.println("All pdf files have been extracted as images");
	}
}
